package com.itheima.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private EmpService empService;

    @Override
    public boolean save(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
        return true;
    }


    @Override
    public PageResult page(String name, LocalDate begin, LocalDate end, Integer page, Integer pageSize) {
        /*PageHelper.startPage(page, pageSize);

        List<Clazz> dataList = clazzMapper.list(name,begin,end);
        Page<Clazz> p = (Page<Clazz>) dataList;

        return new PageResult(p.getTotal(), p.getResult());*/
        Page<Clazz> page1 = Page.of(page, pageSize);
        page1 = page(page1);
        List<Clazz> records = page1.getRecords();
        List<Integer> collect = records.stream().map(Clazz::getMasterId).collect(Collectors.toList());
        List<Emp> empList = empService.listByIds(collect);
        if(!empList.isEmpty()){
            records.stream().forEach(clazz ->{
                empList.stream().filter(emp -> emp.getId().equals(clazz.getMasterId()))
                        .findFirst()
                        .ifPresent(emp -> clazz.setMasterName(emp.getName()));
            });
        }

        return new PageResult<>(page1.getTotal(), records);
        //return null;
    }


    /*@Override
    public Clazz getInfo(Integer id) {
        return clazzMapper.selectById(id);
    }*/

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateById(clazz);
    }

    @Override
    public void deleteById(Integer id) {
        //1. 查询班级下是否有学员
        Integer count = studentMapper.countByClazzId(id);
        if(count > 0){
            throw new BusinessException("班级下有学员, 不能直接删除~");
        }
        //2. 如果没有, 再删除班级信息
        clazzMapper.deleteById(id);
    }

    /*@Override
    public List<Clazz> findAll() {
        return clazzMapper.selectList(null);
    }*/
}
